package com.integral.conf;

import cn.hutool.core.util.ObjectUtil;
import com.integral.system.domain.SysUserDo;
import com.integral.system.position.service.CfgPositionIntegralService;
import com.integral.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CfgPositionIntegralService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("######[用户授权开始]######");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前对象
        Subject subject = SecurityUtils.getSubject();
        //拿到User
        SysUserDo user = (SysUserDo) subject.getPrincipal();
        List<String> roles = roleService.getRolesByUser(Long.toString(user.getUserNo()));
        //设置用户权限
        //info.addStringPermission("*");
        //设置用户角色
        info.addRoles(roles);
        log.info("######[用户授权结束]######");
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("[######[用户认证开始]######]");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //查询用户信息 --- 用户登录名称必须唯一
        SysUserDo user = sysUserService.getUserByName(token.getUsername());
        if (ObjectUtil.isEmpty(user)){
            throw new UnknownAccountException("当前用户不存在");
        }

        //可以加密，MD5:e10adc3949ba59abbe56e057f20f883e  MD5:盐值加密
        //密码认证，shiro做
        log.info("[######[用户认证结束]######]");
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }

}
